import { storeToRefs } from "pinia";
import { useComponent } from "@visual/stores";
import type { Component } from "@visual/types";
import { divide, multiply } from "mathjs";

const componentStore = useComponent();
const { componentData: componentDataStore, canvasStyleData, curComponentIndex } = storeToRefs(componentStore);
const { setCurComponent, setComponentData, setCanvasStyle } = componentStore;
const needToChangeAttrs: string[] = ["width", "height", "top", "left", "fontSize", "padding"];

function deepCopy(target) {
  if (typeof target == "object") {
    const result = Array.isArray(target) ? [] : {};
    for (const key in target) {
      if (typeof target[key] == "object") {
        result[key] = deepCopy(target[key]);
      } else {
        result[key] = target[key];
      }
    }

    return result;
  }

  return target;
}
// 根据比例缩放组件尺寸
export function changeComponentsSizeWithScale(scale: number): void {
  const componentData: any[] = deepCopy(componentDataStore.value);
  componentData.forEach((component: Component) => {
    Object.keys(component.style).forEach((key: string) => {
      if (needToChangeAttrs.includes(key)) {
        let newKey: number;

        // 否则根据当前画布的比例计算新的属性值
        newKey = parseFloat((((component.style[key] as number) / canvasStyleData.value.scale) * scale).toFixed(4));

        if (key == "top" || key == "left") {
          if (component.onlyScalePos) {
            //临时方案，位置修正，为什么这么做尤其时dx/2 我也很懵逼，我猜是放大时width height未参与放大，但是原本的算法里默认放大width和height影响到了位置,部分组件还是有些位移在放大时
            let dx = (component.style["width"] / canvasStyleData.value.scale) * scale - component.style["width"];
            let dy = (component.style["height"] / canvasStyleData.value.scale) * scale - component.style["height"];
            newKey = newKey + (key === "top" ? dy : dx);
          }
          component.style[key] = newKey;
        } else if (!component.onlyScalePos) {
          component.style[key] = newKey === 0 ? 1 : newKey;
        }
      }
    });
  });

  setComponentData(componentData);
  // 更新后的组件数据
  setCurComponent({
    component: componentData[curComponentIndex.value],
    index: curComponentIndex.value
  });

  // 更新画布的比例
  setCanvasStyle({ scale });
}

const needToChangeAttrs2: string[] = ["width", "height", "fontSize", "padding"];

export function changeComponentSizeWithScale(component): void {
  Object.keys(component.style).forEach((key: string) => {
    if (needToChangeAttrs2.includes(key)) {
      if (key === "fontSize" && component.style[key] === "") return;

      component.style[key] = format(component.style[key] as number, canvasStyleData.value.scale);
    }
  });
}

function format(value: number, scale: number): number {
  return multiply(value, divide(parseFloat(scale.toString()), 100)) as number;
}
